package cn.hx.admin.aop;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
@Component
@Aspect
public class PageAop {
    // 分页AOP
    @Around("execution(* cn.hx.admin.controller.*.queryByPage(..))")
    public Object page(ProceedingJoinPoint joinPoint) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String page = request.getParameter("page");
        String size = request.getParameter("size");
        String orderBy = request.getParameter("orderBy");
        System.out.println(orderBy);
        if (StringUtils.hasText(page) && StringUtils.hasText(size)) {
            Page<Object> objects = PageHelper.startPage(Integer.parseInt(page), Integer.parseInt(size), StringUtils.hasText(orderBy) ? orderBy : null);
            joinPoint.proceed();
            return ResponseEntity.ok(new PageInfo<>(objects));
        }
        Object proceed = joinPoint.proceed();
        System.out.println("进入aop ");
        return proceed;
    }
}
